import { defineStore } from 'pinia'
import type { SearchParams, SearchFilters } from '../types/search'

// 导入全局类型
import '../types/global'

/**
 * 搜索状态管理
 */
export const useSearchStore = defineStore('search', {
  state: () => ({
    // 搜索关键词
    query: '',
    
    // 搜索结果
    results: [] as any[],
    
    // 分页信息
    pagination: {
      page: 1,
      limit: 50,
      total: 0,
      totalPages: 0
    },
    
    // 页面大小
    pageSize: 50,
    
    // 当前页
    currentPage: 1,
    
    // 总数
    total: 0,
    
    // 加载状态
    loading: false,
    
    // 搜索建议
    suggestions: {
      query: [] as any[],
      camera_make: [] as any[],
      camera_model: [] as any[],
      tags: [] as any[],
      albums: [] as any[]
    },
    
    // 热门标签
    popularTags: [] as any[],
    
    // 相机品牌列表
    cameraMakes: [] as any[],
    
    // 相机型号列表
    cameraModels: [] as any[],
    
    // 搜索历史
    searchHistory: [] as string[],
    
    // 当前筛选条件
    filters: {
      dateFrom: null,
      dateTo: null,
      cameraMake: '',
      cameraModel: '',
      rating: null,
      tags: [] as number[],
      albums: [] as number[],
      bounds: null // 地理位置边界
    }
  }),
  
  getters: {
    // 获取搜索结果总数
    resultCount: (state) => state.total,
    
    // 获取当前页结果
    currentPageResults: (state) => state.results,
    
    // 获取当前页
    currentPage: (state) => state.currentPage,
    
    // 获取页面大小
    pageSize: (state) => state.pageSize,
    
    // 获取搜索建议
    getSuggestionsByType: (state) => (type: string) => {
      return state.suggestions[type as keyof typeof state.suggestions] || []
    }
  },
  
  actions: {
    // 执行搜索
    async search(params: any = {}) {
      this.loading = true
      
      try {
        const response = await window.electronAPI.search.query({
          query: params.query || this.query,
          filters: params.filters || this.filters,
          page: params.page || this.currentPage,
          limit: params.limit || this.pageSize
        })
        
        if (response.success) {
          this.results = response.data.photos
          this.total = response.data.total
          this.currentPage = response.data.page
          this.pageSize = response.data.limit
          
          // 更新搜索关键词
          if (params.query) {
            this.query = params.query
            this.addToSearchHistory(params.query)
          }
          
          // 更新筛选条件
          if (params.filters) {
            this.filters = { ...this.filters, ...params.filters }
          }
        } else {
          throw new Error(response.error)
        }
      } catch (error) {
        console.error('搜索失败:', error)
        throw error
      } finally {
        this.loading = false
      }
    },
    
    // 获取搜索建议
    async getSuggestions(type: string, query: string) {
      try {
        const response = await window.electronAPI.search.getSuggestions({ type, query })
        
        if (response.success) {
          this.suggestions[type as keyof typeof this.suggestions] = response.data
          return response.data
        } else {
          throw new Error(response.error)
        }
      } catch (error) {
        console.error('获取搜索建议失败:', error)
        throw error
      }
    },
    
    // 获取热门标签
    async fetchPopularTags(limit = 20) {
      try {
        const response = await window.electronAPI.search.getPopularTags({ limit })
        
        if (response.success) {
          this.popularTags = response.data
          return response.data
        } else {
          throw new Error(response.error)
        }
      } catch (error) {
        console.error('获取热门标签失败:', error)
        throw error
      }
    },
    
    // 获取相机品牌列表
    async fetchCameraMakes() {
      try {
        const response = await window.electronAPI.search.getCameraMakes()
        
        if (response.success) {
          this.cameraMakes = response.data
          return response.data
        } else {
          throw new Error(response.error)
        }
      } catch (error) {
        console.error('获取相机品牌列表失败:', error)
        throw error
      }
    },
    
    // 获取相机型号列表
    async fetchCameraModels(make?: string) {
      try {
        const response = await window.electronAPI.search.getCameraModels({ make })
        
        if (response.success) {
          this.cameraModels = response.data
          return response.data
        } else {
          throw new Error(response.error)
        }
      } catch (error) {
        console.error('获取相机型号列表失败:', error)
        throw error
      }
    },
    
    // 设置搜索关键词
    setQuery(query: string) {
      this.query = query
    },
    
    // 设置筛选条件
    setFilters(filters: any) {
      this.filters = { ...this.filters, ...filters }
    },
    
    // 重置筛选条件
    resetFilters() {
      this.filters = {
        dateFrom: null,
        dateTo: null,
        cameraMake: '',
        cameraModel: '',
        rating: null,
        tags: [],
        albums: [],
        bounds: null
      }
    },
    
    // 添加到搜索历史
    addToSearchHistory(query: string) {
      // 移除重复项
      this.searchHistory = this.searchHistory.filter(item => item !== query)
      
      // 添加到开头
      this.searchHistory.unshift(query)
      
      // 限制历史记录数量
      if (this.searchHistory.length > 10) {
        this.searchHistory = this.searchHistory.slice(0, 10)
      }
    },
    
    // 清空搜索历史
    clearSearchHistory() {
      this.searchHistory = []
    },
    
    // 设置当前页
    setPage(page: number) {
      this.currentPage = page
    },
    
    // 设置每页数量
    setLimit(limit: number) {
      this.pageSize = limit
    },
    
    // 清空搜索结果
    clearResults() {
      this.results = []
      this.query = ''
      this.total = 0
      this.currentPage = 1
      this.pageSize = 50
    }
  }
})